/******************************************************************************
 * @File name   :      ApplicationInitServlet.java
 *
 * @Author      :      zhangyao
 *
 * @Date        :      2011-6-20
 *
 * @Copyright Notice: 
 * Copyright (c) 2014 DMS, Inc. All  Rights Reserved.
 * This software is published under the terms of the DMS Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * 2011-6-20 上午10:16:36        zhangyao     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.framework.init;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.servlet.http.HttpServlet;

import com.cap.bts.commonfunc.common.service.IConcurrentLockService;
import com.cap.bts.commonfunc.jms.constant.JMSConfigurationConstants;
import com.cap.bts.framework.cache.constant.CacheType;
import com.cap.bts.framework.cache.service.ICacheManager;
import com.cap.bts.framework.cache.util.CacheUtil;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.ApplicationContextUtil;
import com.cap.bts.framework.common.util.SyncThread;
import com.cap.bts.framework.message.constant.DestType;
import com.cap.bts.framework.message.service.IJMSWrapper;
import com.cap.bts.framework.message.service.impl.JMSWrapper;
import com.cap.bts.framework.message.util.JMSConfigUtil;
import com.cap.bts.framework.scheduler.service.ISchedulerService;
import com.cap.bts.framework.sms.service.IMessageSender;
import com.cap.bts.framework.sms.service.impl.MessageSenderImpl;

/**
 *
 */
public class ApplicationInitServlet extends HttpServlet {


    private ICacheManager cacheManager = null;

    public static String factoryKey;
    private static String DMS_TOKEN_FILE = "dms_token.lok";
    
    @Override
    public void init() {
        try {
            initScheduler();
        } catch (AppException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
//        try {
//        	initJms();
//        } catch (AppException e) {
//            System.out.println("Init SMS service failed:" + e.getLocalizedMessage());
//        }
//        initCache();       
//        String tokenFilePath = FileUtils.getTokenFilePath(DMS_TOKEN_FILE);
//        ConcurrentServiceThread thread = new ConcurrentServiceThread(tokenFilePath);
//        failoverService.execute(thread);
//        
//        clearConcurrentLocks();
    }
    
    public void initJms() throws AppException{
        try {
            JMSConfigUtil.loadJMSConfig();  
           // factoryKey = JMSConfigurationConstants.WEBLOGIC_CONNECTION_FACTORY;
        } catch (Exception e) {
            System.out.println("Init JMS failed:" + e.getLocalizedMessage());
        }
    }
    
    public void shutdownJMS() throws AppException {
    }
    
    public void shutdownScheduler() throws AppException{
        try {
            ISchedulerService service = (ISchedulerService)ApplicationContextUtil.getBean("quartzSchedulerServiceImpl");
            service.destroy();
        } catch (Exception e) {
            System.out.println("Shutdown Scheduler failed:" + e.getLocalizedMessage());
        }
    }
    
    
    public void initScheduler() throws AppException{
        try {
            ISchedulerService service = (ISchedulerService)ApplicationContextUtil.getBean("quartzSchedulerServiceImpl");
            service.init();
        } catch (Exception e) {
            System.out.println("Init Scheduler failed:" + e.getLocalizedMessage());
        }
    }
    
    public void initSMSService() throws AppException{
        try {
            IMessageSender messageSender = new MessageSenderImpl();
            messageSender.startSMSService();
            System.out.println("Start SMS Service Done!");
        } catch (Exception e) {
            System.out.println("Init SMS service failed:" + e.getLocalizedMessage());
        }
    }
    
    public void shutdownSMSService() throws AppException{
        try {
            IMessageSender messageSender = new MessageSenderImpl();
            messageSender.stopSMSClientEngine();
            System.out.println("Stop SMS Service Done!");
        } catch (Exception e) {
            System.out.println("Stop SMS service failed:" + e.getLocalizedMessage());
        }
    }
    
//    public void initCache() {
//        try {
//            cacheManager = CacheUtil.getCacheManager(CacheType.Memcached);
//            cacheManager.init("memcached.xml");
//        } catch (Exception e) {
//            System.out.println("Init Cache service failed:" + e.getLocalizedMessage());
//        }
//    }
    
    public void clearConcurrentLocks(){
    	try{
        	IConcurrentLockService concurrentLockService = (IConcurrentLockService)ApplicationContextUtil.getBean("concurrentLockService");
        	concurrentLockService.clearAllConcurrentLock();
    	}catch(Exception e ){
    		System.out.println("Clear All Concurrent Locks Failed: " + e.getLocalizedMessage());
    	}
    }
    
    public class ConcurrentServiceThread extends SyncThread {

        /**
         * @Date        :      Dec 8, 2011
         * @param token
         */
        public ConcurrentServiceThread(String token) {
            super(token);
        }

        /**
         * {@inheritDoc} 
         * overridden:
         * @Date        :      Sep 21, 2011
         * @see com.cap.bts.framework.common.util.SyncThread#handleThreadTask()
        **/
        @Override
        public void handleThreadTask() {
            try {
                ApplicationInitServlet.this.initScheduler();
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    System.out.println("Sleep before init jms failed.");
                }
                ApplicationInitServlet.this.initJms();
                
                System.out.println("start DMS done");
            } catch (AppException e) {
                System.out.println("Init DMS application servlet failed: " + e.getLocalizedMessage());
            }
        }
        
        @Override
        public void releaseResource() {
            try {
                ApplicationInitServlet.this.shutdownJMS();
                ApplicationInitServlet.this.shutdownScheduler();
                ApplicationInitServlet.this.shutdownSMSService();
                System.out.println("release DMS done");
            } catch (AppException e) {
                System.out.println("Release DMS application servlet failed: " + e.getLocalizedMessage());
            }
        }
    }
}